package com.tmpt.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import com.tmpt.service.IMenuService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.tmpt.dto.A2UserDto;
import com.tmpt.service.ISecurityV2Service;

@Service
public class MyUserDetailServiceImpl implements UserDetailsService{

	//@Resource private ISecurityV2Service securityV2Service;
	@Resource private IMenuService menuService;

	@SuppressWarnings("deprecation")
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();

		A2UserDto userDto = menuService.getUserByLoginname(username);

		Set<String> authNameSet = userDto.getMenu2AuthList();
		for(String authName: authNameSet){
			GrantedAuthorityImpl grantedAuthority = new GrantedAuthorityImpl(authName);
			authSet.add(grantedAuthority);
		}

		Collection<GrantedAuthority> grantedAuths = authSet;

		String password = userDto.getPassword();
		boolean enabled = userDto.getDeleteFlag()==0? true: false;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		User userDetails = new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked,grantedAuths);


		return userDetails;
	}

}
